#include "burner.h"

#define MAX_AUDIO_BUFFER 2

static bool bAudioOkay = false;
static INT16 *pSoundBuffers[MAX_AUDIO_BUFFER] = {0};
static INT32 nSoundBuffersPos = 0;

static void AudioBufferInit()
{
    nAudSegLen = (nBurnSoundRate * 100 + (nBurnFPS >> 1)) / nBurnFPS;
    nBurnSoundLen = nAudSegLen;

    size_t nSize = (nAudSegLen << 2) * sizeof(INT16);
    for (INT32 i = 0; i < MAX_AUDIO_BUFFER; i++)
    {
        pSoundBuffers[i] = (INT16 *)malloc(nSize);
        if (pSoundBuffers[i])
            memset(pSoundBuffers[i], 0, nSize);
    }
    nSoundBuffersPos = 0;
    pBurnSoundOut = pSoundBuffers[nSoundBuffersPos];
}

static void AudioBufferDeinit()
{
    for (INT32 i = 0; i < MAX_AUDIO_BUFFER; i++)
    {
        if (pSoundBuffers[i])
            free(pSoundBuffers[i]);
        pSoundBuffers[i] = NULL;
    }
    nSoundBuffersPos = 0;
    pBurnSoundOut = NULL;
}

UINT32 BurnUpdateSoundOut(INT16 *pIn, INT16 **pOut)
{
    if (bBurnSound && pIn)
        audio_batch_cb(pIn, nBurnSoundLen);
    nSoundBuffersPos = (nSoundBuffersPos + 1) % MAX_AUDIO_BUFFER;
    *pOut = pSoundBuffers[nSoundBuffersPos];

    return 0;
}

UINT32 BurnAudioOutInit()
{
    if (bAudioOkay)
        BurnAudioOutExit();

    AudioBufferInit();
    bAudioOkay = 1;

    return 0;
}

UINT32 BurnAudioOutExit()
{
    AudioBufferDeinit();
    bAudioOkay = 0;

    return 0;
}
